package com.wuwei.jy.interceptor;

import java.sql.PreparedStatement;
import java.sql.ResultSet;

import java.util.Properties;
import java.sql.Connection;

import org.apache.ibatis.executor.parameter.ParameterHandler;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.apache.log4j.Logger;

import com.wuwei.jy.domain.BaseExample;
import com.wuwei.jy.domain.Page;

/**
 * 分页截拦器
 * 
 * @author Administrator
 *
 */
@Intercepts({ @Signature(type = StatementHandler.class, method = "prepare", args = { Connection.class }) })
public class PagerIntercepter implements Interceptor {
	public static Logger log = Logger.getLogger(PagerIntercepter.class);
	private String test;

	public Object intercept(Invocation invocation) throws Throwable {
		StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
		MetaObject metaObject = MetaObject.forObject(statementHandler, SystemMetaObject.DEFAULT_OBJECT_FACTORY,
				SystemMetaObject.DEFAULT_OBJECT_WRAPPER_FACTORY);
		MappedStatement mappedStatement = (MappedStatement) metaObject.getValue("delegate.mappedStatement");
		// 配置文件中SQL语句的ID
		String id = mappedStatement.getId();
		// if(id.matches(".+ByPage$")) {
		if (id.matches(".+Example$")) {

			BoundSql boundSql = statementHandler.getBoundSql();
			// 原始的SQL语句
			String sql = boundSql.getSql();
			BaseExample parameter = (BaseExample) boundSql.getParameterObject();
			Page page = parameter.getPager();
			if (page != null) {
				// 查询总条数的SQL语句
				String countSql = "select count(*) from (" + sql + ")a";
				Connection connection = (Connection) invocation.getArgs()[0];
				PreparedStatement countStatement = connection.prepareStatement(countSql);
				ParameterHandler parameterHandler = (ParameterHandler) metaObject.getValue("delegate.parameterHandler");
				parameterHandler.setParameters(countStatement);
				ResultSet rs = countStatement.executeQuery();

				if (rs.next()) {
					page.setTotalNumber(rs.getInt(1));
				}
				// 改造后带分页查询的SQL语句
				String pageSql = sql + " limit " + page.getDbIndex() + "," + page.getDbNumber();
				metaObject.setValue("delegate.boundSql.sql", pageSql);
			}
		}
		return invocation.proceed();
	}

	public Object plugin(Object arg0) {

		// System.out.println(this.test);
		log.debug(this.test);
		return Plugin.wrap(arg0, this);
	}

	public void setProperties(Properties properties) {
		// TODO Auto-generated method stub
		this.test = properties.getProperty("test");

	}

}
